// pages/nfct/nfct.js
let nfc = require("../../utils/nfctoolsMifareClassic.js")
const {read} = require("../../utils/nfctoolsMifareClassic");
Page({
  nfc: null,
  mifareClassic:null,
  /**
   * 页面的初始数据
   */
  data: {
    sectorIndex: 0,
    authKey: "FFFFFFFFFFFF",
    useAuthKey: "A",
    defaultKey: ["FFFFFFFFFFFF", "D3F7D3F7D3F7", "A0A1A2A3A4A5", "B0B1B2B3B4B5", "AABBCCDDEEFF", "A0B1C2D3E4F5", "B0B1B2B3B4B5", "000000000000"],
    defaultSector: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
    chekcKeyItems: [
      { value: 'A', name: '密钥A', checked: 'true' },
      { value: 'B', name: '密钥B' },
    ],
    result: [],
    mifareClassic :null,
    status:2,
    tagId:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    //调用wx.getNFCAdapter()获取NFC适配器实例
    const adapter = wx.getNFCAdapter();
    console.log("获取NFC实例", adapter)
    this.nfc = adapter;
    let that = this
    adapter.onDiscovered(res => {
      console.log("读取到卡片了", res);
      let tagId = that.arrBuffer2Str(res.id);
      that.setData({status:1,tagId:tagId})
      console.log("获取到tagID：", tagId);
      if (res.techs.includes(adapter.tech.mifareClassic)) {
        console.log('发现' + adapter.tech.mifareClassic + '卡');
        that.mifareClassic = adapter.getMifareClassic();

        that.mifareClassic.connect({
          success: res => {
            console.log("设备已连接", res)
          }
        })
        that.mifareClassic.isConnected({
          success: function (isConnected) {
            console.log('成功连接', isConnected);
            that.data.result = []
            that.setData({result:[]})
            that.readAll(0)
          }
        });
      }
    })
    adapter.startDiscovery({
      fail(err) {
        console.log('failed to discover:', err)
      }
    })
  },
  onHide() {
    if (this.nfc) {
      this.nfc.stopDiscovery()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    nfc.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  auth:function (s,read,successFn) {
    let that = this
    this.mifareClassic.transceive({
      data: new Uint8Array([
          0x60,
        s * 4,
        0x11, 0x22, 0x33, 0x44,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
      ]).buffer,
      success: successFn,
      fail: function (err) {
        console.log('默认密钥鉴权失败', err);
        // 用新密钥试试
        if (read === false) {
          that.mifareClassic.transceive({
            data: new Uint8Array([
              0x61,
              s * 4,
              0x11, 0x22, 0x33, 0x44,
              0x20,0xCE,0x20,0xCE,0xBA,0x5E
            ]).buffer,
            success: successFn,
            fail: function (err) {
              console.log('鉴权失败', err);
            }
          })
        }else{
          that.mifareClassic.transceive({
            data: new Uint8Array([
              0x60,
              s * 4,
              0x11, 0x22, 0x33, 0x44,
              0x31,0x7E,0xF3,0x18,0x3A,0x5E
            ]).buffer,
            success: successFn,
            fail: function (err) {
              console.log('鉴权失败', err);
            }
          })
        }
      }
    })
  },
  readAll: function (s) {
    let mifareClassic = this.mifareClassic
    let that = this
    this.auth(s,true,function (res) {
      console.log('发送数据并解密成功, 接收数据如下:', res);
      let completeI = 0;
      for (let i = 0;i <= 3;i++) {
        mifareClassic.transceive({
          data: new Uint8Array([0x30, s*4 + i]).buffer,
          success: function (res) {
            let content = that.arrBuffer2Str(res.data)
            that.data.result.push(content)
            that.setData({
              result:that.data.result
            })
            console.log('读取扇区-'+s+';块-'+i+'数据:',content);
            completeI++
            if (completeI === 4&&s < 15) {
              that.readAll(++s)
            }
          },
          fail: function (err) {
            that.data.result.push("err")
            that.setData({
              result:that.data.result
            })
            console.log('失败', err);
            completeI++
          },
        })
      }
    })
  },
  arrBuffer2Str:function (arr){
    let content = ""
    for (var o = new Uint8Array(arr), r = 0; r < o.length; r++) {
      var c = o[r].toString(16);
      c.length < 2 && (c = "0" + c), r == o.length - 1 ? content += c : content += c + ":";
    }
    return content
  },
  writeAllClick: function () {
    this.writeAll(0)
  },
  writeAll: function (s) {
    console.log('正在写入扇区-'+s+'密钥');
    let mifareClassic = this.mifareClassic
    let that = this
    this.auth(s,false,function (res) {
      mifareClassic.transceive({
        data: new Uint8Array([
          // 写入指令
          0xA0,
          // 扇区块
          (s+1) * 4 - 1,
          // 密钥a
          0x31,0x7E,0xF3,0x18,0x3A,0x5E,
          // 权限 a 只读 b 读写
          0x08,0x77,0x8F,0x69,
          // 密钥b
          0x20,0xCE,0x20,0xCE,0xBA,0x5E
        ]).buffer,
        success: function (res) {
          let content = that.arrBuffer2Str(res.data)
          console.log('写入扇区-'+s+'密钥成功',content);
          wx.showToast({
            title: '写入扇区-'+s+'密钥成功',
            icon: "none",
            mask: true,
          })
          if (s < 15) {
            that.writeAll(++s)
          }
        },
        fail: function (err) {
          console.log('写入失败',s, err);
        },
      })
    })
  },
})